package pl.edu.pw.elka.tinyrepo.trash;

import java.util.HashMap;
import java.util.Map;

import pl.edu.pw.elka.tinyrepo.common.Response;

/**
 * Fabryka odpowiedzi 
 * 
 * @author Anna Stępień
 * @version 12-12-2011
 *
 */
public class ResponseFactory
{
	/** Instancja fabryki ResponseFactory */
	private static ResponseFactory instance = null;
	/** Mapa przechowujaca zarejstrowane klasy Response */
	private Map<String, Class<? extends Response> > responseMap =
			new HashMap<String, Class<? extends Response>>();
	
	/**
	 * Zwraca instancję fabryki 
	 * 
	 * @return instance instancja fabryki
	 * 
	 */
	public synchronized ResponseFactory getInstance()
	{
		if (instance == null)
			instance = new ResponseFactory();
		return instance;
	}
	
	/**
	 * Zwraca obiekt Response dla zadanej nazwy
	 * 
	 * @param responseName nazwa Response
	 * @return response obiekt Response
	 * @throws UnsupportedOperationException 
	 * 
	 */
	public Response getResponse(final String responseName) throws UnsupportedOperationException
	{
		Response response = null;
		Class<? extends Response> responseClass = responseMap.get(responseName);
		if (responseClass == null)
		{
			throw new UnsupportedOperationException("Unsupported response: " + responseName);
		}
		try
		{
			response = responseClass.newInstance();
		}
		catch(InstantiationException e)
		{
			e.printStackTrace();
		}
		catch(IllegalAccessException e)
		{
			e.printStackTrace();
		}
		
		return response;
	}
	
	/**
	 * Rejestruje nowy Response
	 * 
	 * @param responseName nazwa Response
	 * @param responseClass klasa Response
	 * 
	 */
	public void registerResponse(final String responseName, Class<? extends Response> responseClass)
	{
		responseMap.put(responseName, responseClass);
	}
	
	private ResponseFactory()
	{
		registerResponse("GET", Response.class);
	}
}
